/* Schema and module dependencies */

var crypto = require('crypto'),
    User = require('../schema/UserSchema').UserSchema;

/**
 * Short function to return a md5-hashed string 
 * @param str {String} : Any string, usually a password or e-mail
 *
 * @return hash {String} : A md5-hashed version of the parameter string
 **/

var md5 = function(str) {
    return crypto.createHash('md5').update(str).digest('hex');
};

/**
 * Finds all Users that satisfy the given parameters.
 * See API documentation: GET /users/
 *
 * @param req  {HTTP Request}  : HTTP GET request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON array of User objects
 **/

exports.index = function(req, res) {
    // Don't return password or e-mail in the API call, for obvious reasons
    var query = User.find().exclude('password', 'email', '_id');
    
    // Filter by range
    if (req.query.range) { 
        query.limit(req.query.range); 
    }
    
    // Use regular expressions to do a "starts with" filter
    if (req.query.starts_with) {
        var regexFilter = new RegExp("^" + req.query.starts_with + ".*");
        query.regex('name', regexFilter);
    }

    // Filter by Google ID
    if (req.query.google_id) {
        query.where('google_id').equals(req.query.google_id);
    }
    
    query.exec(function(err, users) {
        if (err) { 
            console.log(err); 
        } else {
            res.json(users);
        }
    });
};

/**
 * Creates a User object using the parameters found in the request body.
 * See API documentation: POST /users/
 *
 * @param req  {HTTP Request}  : HTTP POST request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error
 **/

exports.create = function(req, res) {
    // TODO: add validation checks
    var newUser = new User(
        {
            id           : Math.floor(Math.random() * 9000000) + 1000000,
            name         : req.body.name,
            google_id    : req.body.google_id,
            avatar       : req.body.avatar,
            email        : req.body.email,
            games_played : 0,
            points       : 0,
            date         : new Date().toISOString()
        }
    );
    newUser.save(function(err) {
        // TODO: add error JSON messages
        if (err) { console.log(err); }
        var returnBody = {
            success : true,
            id      : newUser.id,
            code    : 100,
            message : "User successfully added to the database."
        };
        res.json(returnBody);
    });
};

/**
 * Finds a single Gene object with the given gene ID.
 * See API documentation: GET /genes/[id]
 *
 * @param req  {HTTP Request}  : HTTP GET request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON representation of desired Gene object
 **/

exports.show = function(req, res) {
    var query = User.findOne()
        .where('id').equals(req.params.user)
        .exclude('email', '_id');
    query.exec(function(err, user) {
        // TODO: JSON error messages
        if (err) { console.log(err); }
        res.json(user);
    });
};

/**
 * Updates a single User object with the given username.
 * Accepts partial representations of the User object.
 * See API documentation: PUT /users/[name]
 *
 * @param req  {HTTP Request}  : HTTP PUT request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error.
 **/

exports.update = function(req, res) {
    var updatedDoc = {};

    if (req.body.games_played) { updatedDoc.games_played = req.body.games_played; }
    if (req.body.points) { updatedDoc.points = req.body.points; }

    User.update({id: req.params.user}, updatedDoc, function(err) {
        if (err) { 
            // TODO: JSON error messages
            console.log(err);
        } else {
            var returnBody = {
                success : true,
                code    : 200,
                message : "User successfully updated in the database."
            };
            res.json(returnBody);
        }
    });
};

/**
 * Deletes a single User object with the given username.
 * See API documentation: DELETE /users/[name]
 *
 * @param req  {HTTP Request}  : HTTP DELETE request passed from the route
 * @param res  {HTTP Response} : Waiting HTTP response passed from the route
 *
 * @response {JSON Object}     : JSON object representing success or error.
 **/

exports.destroy = function(req, res) {
    User.remove({id: req.params.user}, function(err) {
        if (err) {
            // TODO: JSON error messages 
            console.log(err);
        } else {
            var returnBody = {
                success : true,
                code    : 300,
                message : "User successfully deleted from the database."
            };
            res.json(returnBody);
        }
    });
};
